package com.scx.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.scx.entity.Orders;
import com.scx.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    //TODO 改为MQ延时队列
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", new Date());
        //15分钟前
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时未支付");
            orderMapper.updateById(orders);
        });
    }

    /**
     * 处理打烊后仍未完成订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理打烊后仍未完成订单：{}", new Date());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            orderMapper.updateById(orders);
        });
    }

    /**
     * 返回time之前，状态为status的订单
     * @param status
     * @param time
     * @return
     */
    List<Orders> getByStatusAndOrdertimeLT(Integer status, LocalDateTime time){
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getStatus,status).lt(Orders::getOrderTime,time);
        return orderMapper.selectList(lqw);
    }
}
